//
//  requsetFinished.m
//  HeroCar
//
//  Created by ZC on 15/1/20.
//  Copyright (c) 2015年 SZZCIT. All rights reserved.
//

#import "CommunicateWithService.h"
#import "ASIFormDataRequest.h"
#import "BaseViewController.h"
#import "LoginViewController.h"
#import "AppDelegate.h"

@implementation CommunicateWithService

+(BOOL)communicateWithServiceApiName:(NSString *)api finishSelector:(SEL)finished failSelector:(SEL)failed delegateObj:(id)delegate
{
//    BaseViewController *VC=(BaseViewController *)delegate;
//    
//    [VC showWait:@"" view:VC.view.window];
    
    BaseViewController *VC = (BaseViewController *)delegate;
    
    NSString *urlLogin=[NSString stringWithFormat:@"%@%@",__URL__,api];
    
    NSURL *postURL=[NSURL URLWithString:urlLogin];
    
    VC.asiFDR=[[ASIFormDataRequest alloc] initWithURL:postURL];
    
    AppDelegate *appdelegate = [[UIApplication sharedApplication] delegate];
    
    [VC.asiFDR setPostValue:appdelegate.userId forKey:@"userId"];
    
    [VC.asiFDR setPostValue:@"zh-CN" forKey:@"Accept-Language"];
    
    [VC.asiFDR setTimeOutSeconds:5.0];
    [VC.asiFDR setDelegate:delegate];
    [VC.asiFDR setDidFinishSelector:finished];
    [VC.asiFDR setDidFailSelector:failed];
    [VC.asiFDR startAsynchronous];

    return NO;
}

+(BOOL)communicateWithService:(NSArray *)keyArr value:(NSArray *)valueArr apiName:(NSString *)api finishSelector:(SEL)finished failSelector:(SEL)failed delegateObj:(id)delegate
{
    if ([delegate isKindOfClass:[LoginViewController class]]) {
//        LoginViewController *VC = (LoginViewController *)delegate;
        
        BOOL equal = keyArr.count == valueArr.count?YES:NO;//键值对数组count是否匹配
        
        if (equal) {
            NSString *urlLogin=[NSString stringWithFormat:@"%@%@",__URL__,api];
            
            NSURL *postURL=[NSURL URLWithString:urlLogin];
            
            //            [VC setAsiFDR:[[ASIFormDataRequest alloc] initWithURL:postURL]];
            
            ASIFormDataRequest *asiFDR = [[ASIFormDataRequest alloc] initWithURL:postURL];
            
            for (int i=0; i<keyArr.count; i++) {
                if ([[valueArr objectAtIndex:i] isKindOfClass:[NSData class]]) {
                    //                [asiFDR setData:[valueArr objectAtIndex:i] forKey:[keyArr objectAtIndex:i]];//上传图片
                    
                    [asiFDR setData:[valueArr objectAtIndex:i] withFileName:@"11" andContentType:@".jpeg" forKey:[keyArr objectAtIndex:i]];
                }
                else
                {
                    [asiFDR setPostValue:[valueArr objectAtIndex:i] forKey:[keyArr objectAtIndex:i]];
                }
            }
            
            AppDelegate *appdelegate = [[UIApplication sharedApplication] delegate];
            
            [asiFDR setPostValue:appdelegate.userId forKey:@"userId"];
            
            [asiFDR setPostValue:@"zh-CN" forKey:@"Accept-Language"];
            
            //        [asiFDR setCompletionBlock:<#^(void)aCompletionBlock#>];
            //        [asiFDR setFailedBlock:]
            [asiFDR setTimeOutSeconds:5.0];
            [asiFDR setDelegate:delegate];
            [asiFDR setDidFinishSelector:finished];
            [asiFDR setDidFailSelector:failed];
            [asiFDR startAsynchronous];
        }
        else
        {
            [gAlert dismiss];
        }
        
        return NO;
    }
    else if([delegate isKindOfClass:[BaseViewController class]])
    {
        BaseViewController *VC = (BaseViewController *)delegate;
        
        BOOL equal = keyArr.count == valueArr.count?YES:NO;//键值对数组count是否匹配
        
        if (equal) {
            NSString *urlLogin=[NSString stringWithFormat:@"%@%@",__URL__,api];
            
            NSURL *postURL=[NSURL URLWithString:urlLogin];
            
            [VC setAsiFDR:[[ASIFormDataRequest alloc] initWithURL:postURL]];
            
            //        VC.asiFDR = [[ASIFormDataRequest alloc] initWithURL:postURL];
            
            for (int i=0; i<keyArr.count; i++) {
                if ([[valueArr objectAtIndex:i] isKindOfClass:[NSData class]]) {
                    //                [asiFDR setData:[valueArr objectAtIndex:i] forKey:[keyArr objectAtIndex:i]];//上传图片
                    
                    [VC.asiFDR setData:[valueArr objectAtIndex:i] withFileName:@"11" andContentType:@".jpeg" forKey:[keyArr objectAtIndex:i]];
                }
                else
                {
                    [VC.asiFDR setPostValue:[valueArr objectAtIndex:i] forKey:[keyArr objectAtIndex:i]];
                }
            }
            
            AppDelegate *appdelegate = [[UIApplication sharedApplication] delegate];
            
            [VC.asiFDR setPostValue:appdelegate.userId forKey:@"userId"];
            
            [VC.asiFDR setPostValue:@"zh-CN" forKey:@"Accept-Language"];
            
            //        [asiFDR setCompletionBlock:<#^(void)aCompletionBlock#>];
            //        [asiFDR setFailedBlock:]
            [VC.asiFDR setTimeOutSeconds:5.0];
            [VC.asiFDR setDelegate:delegate];
            [VC.asiFDR setDidFinishSelector:finished];
            [VC.asiFDR setDidFailSelector:failed];
            [VC.asiFDR startAsynchronous];
        }
        else
        {
            [gAlert dismiss];
        }
        
        return NO;
    }
    return NO;
}

+(NSDictionary *)getDataDic:(NSString *)strResult
{
    NSString *str=[NSString stringWithFormat:@"%@",strResult];
    
//    str = @"{\"resultCode\":\"1001\",\"resultData\":{\"pageSize\":10,\"currentIndex\":-10,\"totalCount\":1,\"currentPage\":0,\"countPage\":1,\"content\":[{\"vehicleId\":\"329097\",\"vin\":\"kllllllllllllllll\",\"csn\":\"\",\"domain\":\"1\",\"series\":\"1\",\"model\":\"1\",\"phase\":\"1\",\"buildDate\":\"Mar 6, 2015 12:00:00 AM\",\"editlock\":\"0\",\"plant\":\"1\",\"auditGroup\":\"1\",\"shiftDate\":\"Mar 6, 2015 12:00:00 AM\",\"engine\":\" \",\"transmission\":\"1\",\"color\":\"1\",\"defect_info\":\" \",\"repair_info\":\"\",\"plantListDesc\":\"SAIC MOTOR\",\"domainListDesc\":\"SAIC MOTOR\",\"auditGroupListDesc\":\"Plant\",\"seriesListDesc\":\"MG6 MCE\",\"modelListDesc\":\"SAIC MOTOR\",\"phaseListDesc\":\"SOP\",\"plantListDescEn\":\"SOP\",\"domainListDescEn\":\"SAIC MOTOR\",\"auditGroupListDescEn\":\"Plant\",\"seriesListDescEn\":\"MG6 MCE\",\"modelListDescEn\":\"SAIC MOTOR\",\"phaseListDescEn\":\"SAIC MOTOR\"}]}}";
    
    str=[str stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    str=[str stringByReplacingOccurrencesOfString:@"\t" withString:@""];
    str=[str stringByReplacingOccurrencesOfString:@"\r" withString:@""];//替换制表符
    
//    NSStringEncoding enc=CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    
    NSData *data=[str dataUsingEncoding: NSUTF8StringEncoding];
//    NSData *data=[str dataUsingEncoding: enc];
    
    NSError *error;
    
    NSDictionary *strDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
    


    return strDic;
}

//+(BOOL)uploadImageToService:(NSData *)imgData fileName:(NSString *)fileName
//{
//    return NO;
//}

//请求方法
//+(void)method4:(NSData *)imgData fileName:(NSString *)fileName
//{
//    NSString *boundary;
//    NSString *fileParam;
//    NSString *baseUrl;
//    
//    boundary = @"----------V2ymHFg03ehbqgZCaKO6jy";
//    fileParam = @"file";
//    baseUrl = @"http://url/from/server";
//    fileName = @"image.png";//此文件提前放在可读写区域
//    
//    NSURL *uploadURL;
//    //文件路径处理(随意)
//    NSLog(@"请求路径为%@",uploadURL);
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//        
//        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
//        
//        NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
//        //body
//        NSData *body = [self prepareDataForUpload:imgData fileName:fileName];
//        //request
//        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:uploadURL];
//        [request setHTTPMethod:@"POST"];
//        
//        // 以下2行是关键，NSURLSessionUploadTask不会自动添加Content-Type头
//        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
//        [request setValue:contentType forHTTPHeaderField: @"Content-Type"];
//        
//        NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:body completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
//            
//            NSString *message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//            NSLog(@"message: %@", message);
//            
//            [session invalidateAndCancel];
//        }];
//        
//        [uploadTask resume];
//    });
//}

//生成bodyData
-(NSData*) prepareDataForUpload:(NSData *)imgData fileName:(NSString *)fileName
{
//    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//    NSString *documentsDirectory = [paths objectAtIndex:0];
//    NSString *uploadFilePath = [documentsDirectory stringByAppendingPathComponent:fileName];//将图片放在了documents中
//    
//    NSString *lastPathfileName = [uploadFilePath lastPathComponent];
    
    NSMutableData *body = [NSMutableData data];
    
    NSData *dataOfFile = imgData;
    
    if (dataOfFile) {
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", @"----------V2ymHFg03ehbqgZCaKO6jy"] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", @"file", fileName] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"Content-Type: application/zip\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:dataOfFile];
        [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    }
    
    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", @"----------V2ymHFg03ehbqgZCaKO6jy"] dataUsingEncoding:NSUTF8StringEncoding]];
    
    return body;
}

+(NSString *)getRequestFinishedStr:(NSString *)str
{
    @try
    {
        NSString *strJSON=[str substringFromIndex:[str rangeOfString:@"/\">"].location+3 ];
        NSString *strResult=[strJSON substringToIndex:[strJSON rangeOfString:@"</string>"].location ];
        
//        strResult=[JoDes decode:strResult key:@"ausdifa4"];
        
        if ([strResult isEqualToString:@""]) {
            return @"{\"code\":\"0\",\"msg\":\"数据解析失败！\",\"data\":{}}";
        }
        
        return strResult;
    }
    @catch(NSException *exception)
    {
        return @"{\"code\":\"0\",\"msg\":\"数据解析失败！\",\"data\":{}}";
    }
}

@end
